<template>
    <el-dialog v-model="isShow" title="选择引用数据" width="80%" :z-index="10000">
        <TableHeader :buttons="[]">
            <template #refreshAppend>
                <el-input style="width: 400px" v-model="filterParams.title" class="mr-3 w-40" placeholder="请输入标题" clearable></el-input>
                <el-button type="primary" @click="handleSearch('search')">
                    <Icon name="fa fa-search" class="text-white text-sm mr-1"></Icon>查询
                </el-button>
            </template>
        </TableHeader>
        <Table ref="tableRef" :row-key="row => row.id" @row-click="rowClick" :pagination="false" @select="selectRow">
            <template #image>
                <!-- 在插槽内，您可以随意发挥，通常使用 el-table-column 组件 -->
                <el-table-column prop="thumb" label="封面" :align="'center'">
                    <template #default="scope">
                        <el-image
                            @click.stop
                            :src="scope.row.thumb"
                            fit="cover"
                            class="w-10 h-10"
                            :preview-src-list="[scope.row.thumb]"
                            preview-teleported
                            hide-on-click-modal
                        ></el-image>
                    </template>
                </el-table-column>
            </template>
        </Table>
        <!-- <Table ref="tableRef" :row-key="row => row.id" :pagination="false" @select="selectRow"></Table> -->

        <el-dialog v-model="isShowSku" title="商品SKU" width="80%" :z-index="10001">
            <div style="padding: 20px;">
                <el-table :data="sku_list">
                    <el-table-column align="center" property="title" label="商品标题" />
                    <el-table-column align="center" label="封面">
                        <template #default="scope">
                            <el-image :src="scope.row.thumb" fit="cover" class="w-20 h-20"
                                :preview-src-list="[scope.row.thumb]" preview-teleported hide-on-click-modal></el-image>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" property="price" label="采购数量">
                        <template #default="scope">
                            <el-input
                                v-model="scope.row.actual_quantity"
                                style="width: 150px"
                                placeholder="请输入数量"
                                @change="inputQuantity($event,scope.$index)"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column align="center" property="price" label="采购单价">
                        <template #default="scope">
                            <el-input
                                v-model="scope.row.price"
                                style="width: 150px"
                                placeholder="请输入单价"
                                @change="inputUnivalence($event,scope.$index)"
                            />
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-dialog>
        <template #footer>
            <el-button @click="isShow = false"><el-icon class="mr-1 text-slate-500">
                    <CloseBold />
                </el-icon> 取消</el-button>
            <el-button type="primary" :icon="Plus" @click="handleSave">添加</el-button>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { baTableApi } from '/@/api/common'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import { Plus, CloseBold } from '@element-plus/icons-vue'

import { ref, watch, onMounted, provide, reactive , nextTick , useAttrs} from 'vue'
import createAxios from '/@/utils/axios'
// import { inputNumber } from '/@/utils/tools'
const emits = defineEmits(['addProduct'])
let isShow = ref(true) //添加商品弹窗
let isShowSku = ref(false) //修改sku弹窗
let allData: any = ref([]) //当前页面所有的数据
let data: any = ref([]) //所有选择的表单
let addData: any = ref([]) //要添加的行
let edit_id = ref(null)
let sku_list: any = reactive([]) //要编辑的sku列表
const tableRef = ref() //表格实例
let delIds: any = ref([]) //在表内取消勾选的数据（存着为了后面点添加按钮的时候删除数据）
let rowClickIndex = ref() //当前打开弹窗的产品的索引值

let filterParams = ref({
    title: '',
}) // 搜索参数

const attrs = useAttrs()

const props = defineProps({
    modelValue: Boolean,
    purchaserList: Array,
    data: Array
})

watch(
    () => props.modelValue,
    (newVal) => {
        isShow.value = newVal;
    }
);

watch(
    () => props.data,
    (newVal) => {
        data.value = newVal;
    }
);

watch(
    () => allData.value,
    (newVal) => {
        nextTick(() => {
            //改变产品列表时数据回填,勾选回填
            data.value.forEach((item: any) => {
                newVal.forEach((item2: any) => {
                    if(item.demand_sku_id == item2.id && !delIds.value.includes(item.demand_sku_id)) {
                        tableRef.value.getRef().toggleRowSelection(item2, true)
                        item.skus.forEach((sku_item: any) => {
                            item2.skus.forEach((sku_item2: any) => {
                                if(sku_item.demand_sku_id == sku_item2.id) {
                                    sku_item2.actual_quantity = sku_item.actual_quantity
                                    sku_item2.price = sku_item.price
                                    Reflect.set(sku_item2, 'sku_order_id', sku_item.id)
                                }
                            });
                        });
                        
                    }
                })
            })
        })
    }
);

/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/xmwms.purchase.Demand/'),
    {
        pk: 'id',
        column: [
            {
                width: 50,
                type: 'selection',
                align: 'center',
                reserveSelection: true,
            }, {
                label: '商品标题',
                prop: 'title',
                align: 'center',
            },
            {
                label: '封面',
                prop: 'thumb',
                align: 'center',
                render: 'slot',
                slotName: 'image',
                operator: false
            },
            {
                label: '需求数量',
                prop: 'xq_num',// prop: 'actual_quantity',
                align: 'center'
            },
            {
                label: '价格',
                prop: 'money_price',
                align: 'center'
            }
        ],
        dblClickNotEditColumn: ['all'],
    },
    {
        defaultItems: {},
    }
)

let filter = ref(baTable.table.filter)

//搜索操作
const handleSearch = (type: string) => {
    //赋值给baTable的filter对象
    filter.value!.title = filterParams.value.title
    baTable.getIndex()?.then(() => {
        changeData()
     })
}


// let filter = ref(baTable.table.filter)
provide('baTable', baTable)

//取消添加产品弹窗内表格的对应勾选并删除选择的数据
const getSelectionRows = (row: any, isAdd: Boolean) => {
    let select_row = allData.value.find((item:any) => item.id === row.id)
    tableRef.value.getRef().toggleRowSelection(select_row, isAdd)
}

//表格选中行
// const handleSelectionChange = (val: any) => {
    // console.log(val,"选择数据");
    // addData.value = val
// }

//单选行
const selectRow = (selection: any, row: any) => {
    let resultIndex = data.value.findIndex((element: any) => {
        return element.id == row.id
    });
    
    if(resultIndex !== -1) {
        //当前选择项在已有产品（data）中出现
        let resultIndex2 = addData.value.findIndex((element2: any) => {
            return element2.id == row.id
        });
        if(resultIndex2 !== -1) {
            //当前选择项在当前搜索页（addData）中存在
            addData.value.splice(resultIndex2,1)
            delIds.value.push(row.id)
        } else {
            //当前选择项在当前搜索页（addData）中不存在
            addData.value.push(row)
            delIds.value = delIds.value.filter((item:any) => item !== row.id)
            
        }
    } else {
        //当前选择项不在已有产品（data）中出现
        let resultIndex2 = addData.value.findIndex((element: any) => {
            return element.id == row.id
        });
        if(resultIndex2 !== -1) {
             //当前选择项在当前搜索页（addData）中存在
            addData.value.splice(resultIndex2,1)
        } else {
            //当前选择项在当前搜索页（addData）中不存在
            addData.value.push(row)
        }
    }
}

//表格点击行
const rowClick = (row: any) => {
    edit_id.value = row.id
    sku_list = row.skus
    rowClickIndex.value = allData.value.findIndex((element: any) => {
        return element.id === row.id
    });
    isShowSku.value = true
}

//输入数量
const inputQuantity = (val:any,sku_index:any) => {
    allData.value[rowClickIndex.value].skus[sku_index].actual_quantity = val
}

//输入金额
const inputUnivalence = (val:any,sku_index:any) => {
    allData.value[rowClickIndex.value].skus[sku_index].price = val
}

//保存操作
const handleSave = () => {
    data.value = [...addData.value, ...data.value]
    //data数组根据id去重
    const arr = data.value.map((item:any) => {
        return item.id
    })
    data.value = data.value.filter((item:any, index:any) => {
        return arr.indexOf(item.id) === index
    })
    //将取消勾选的数据都删除
    delIds.value.forEach((id: any) => {
        data.value = data.value.filter((item: any) => {
            return item.id !== id
        })
    });
    delIds.value = []

    //赋值
    addData.value = JSON.parse(JSON.stringify(data.value))

    emits('addProduct', data)
    isShow.value = false
}

//搜索出的列表初始化
const changeData = () => {
    allData.value = baTable.table.data
    //添加数据
    allData.value.forEach((item: any) => {
        Reflect.set(item, 'checked', false)
        item.skus.forEach((element: any) => {
            Reflect.set(element, 'actual_quantity', '')
            Reflect.set(element, 'price', '')
            Reflect.set(element, 'checked', false)
        });
    })
}

onMounted(() => {
    filter.value!.platform = attrs.platform

    isShow.value = false
    baTable.table.ref = tableRef.value
    baTable.mount()
    setTimeout(() => {
        baTable.getIndex()?.then(() => {
            baTable.initSort()
            baTable.dragSort()
            changeData()
            if(props.data) {
                data.value = props.data
                addData.value = JSON.parse(JSON.stringify(data.value))//深拷贝赋值
            }
        })
    }, 1000);
})

defineExpose({
    getSelectionRows,
});

</script>

<style scoped lang="scss">
    
</style>
